﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Bouyomichan
{
    internal class BouyomichanTcpClient:IDisposable
    {

        private TcpClient _tcpClient;


        private const int PORTNO = 50001;

        private const string HOSTNAME = "127.0.0.1";

        private const short SPEED = -1;

        private const short TONE = -1;

        private const short COMMAND = 0x0001;

        private const short VOLUME = -1;

        private const short VOICE = 0;

        private const byte CODE = 0;

        


        public BouyomichanTcpClient()
        {
            _tcpClient = new TcpClient();

        }

        public void Connect()
        {
            lock (_tcpClient)
            {
                if (!_tcpClient.Connected) _tcpClient.Connect(HOSTNAME, PORTNO);
            }

            
        }


        public bool Connected
        {
            get
            {
                return _tcpClient.Connected;
            }
        }


        public void Send(string message)
        {
            lock (this)
            {
                using (BinaryWriter writer = new BinaryWriter(new BufferedStream(_tcpClient.GetStream())))
                {

                    byte[] messageBytes = Encoding.UTF8.GetBytes(message);
                    writer.Write(COMMAND);
                    writer.Write(SPEED);
                    writer.Write(TONE);
                    writer.Write(VOLUME);
                    writer.Write(VOICE);
                    writer.Write(CODE);
                    writer.Write(messageBytes.Length);
                    writer.Write(messageBytes);
                }


            }
            


            
        }



        public void Dispose()
        {
            _tcpClient.Close();
        }
    }
}
